package ltd.dujiabao.fake_asyn;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.security.MessageDigest;
import java.util.concurrent.*;

/**
 * @author : DuJiabao
 * @Project : io_test
 * @Time : 2021/5/30 18:57
 * @Desc :
 */
public class Server {
  public static void main(String[] args) throws IOException {
    ServerSocket serverSocket = new ServerSocket(9999);
    ExecutorService threadPool = createThreadPool(3, 1000);  // 初始化一个线程池，最大线程数为3，队列最多可以存放1000个连接

    for (; ; ) {
      Socket socket = serverSocket.accept();
      System.out.println("接收到一个新的连接");
      threadPool.execute(() -> {  // 线程池处理
        try {
          BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
          String msg;
          while ((msg = reader.readLine()) != null) {
            System.out.println(Thread.currentThread().getName() + "接收到信息 ：" + msg);
          }
        } catch (IOException e) {
          e.printStackTrace();
        }
      });
    }
  }

  private static ExecutorService createThreadPool(int maxPoolSize, int queueSize) {
    return new ThreadPoolExecutor(maxPoolSize, maxPoolSize, 120L, TimeUnit.SECONDS, new LinkedBlockingQueue<>(queueSize));
  }
}
